package com.chixing.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.chixing.annotation.AutoIdempotent;
import com.chixing.entity.OrderBase;
import com.chixing.entity.OrderDetail;
import com.chixing.entity.vo.OrderRequest;
import com.chixing.entity.vo.OrderBaseWithDetailsVO;
import com.chixing.service.IOrderBaseService;
import com.chixing.service.impl.SeatStatusService;
import com.chixing.util.Result;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 订单基础信息前端控制器
 * </p>
 *
 * @author smith
 * @since 2025-10-01
 */
@CrossOrigin
@RestController
@RequestMapping("/orderbase")
public class OrderBaseController {

    @Autowired
    private IOrderBaseService orderBaseService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private SeatStatusService seatStatusService;
    // 查询所有订单
    @GetMapping
    public List<OrderBase> getAllOrders() {
        return orderBaseService.getAllOrders();
    }

    // 根据ID查询订单
    @GetMapping("/{id}")
    public OrderBase getOrderById(@PathVariable Integer id) {
        return orderBaseService.getOrderById(id);
    }


    /**
     * 新增订单及详情（强制绑定）
     * @param orderRequest 包含订单基础信息和详情列表的请求对象
     * @return 创建结果
     */
    @PostMapping
    @AutoIdempotent
    public Result saveOrderWithDetails(@RequestBody OrderRequest orderRequest) {
        OrderBase orderBase = orderRequest.getOrderBase();
        List<OrderDetail> orderDetails = orderRequest.getOrderDetails();
        // 检查是否已存在当前用户的相同订单或者已经被预定
        QueryWrapper<OrderBase> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_id", orderBase.getUserId())
                .eq("schedule_id", orderBase.getScheduleId())
                .eq("seat_coordinates", orderBase.getSeatCoordinates());

        OrderBase userExistingOrder = orderBaseService.getOne(userQueryWrapper);
        if (userExistingOrder != null) {
            return Result.saveFail("相同订单已存在或座位已被预定，请返回");
        }

        // 锁定座位
        boolean lockResult = seatStatusService.lockSeatsTemporarily(orderBase.getScheduleId(), orderBase.getSeatCoordinates());
        if (!lockResult) {
            return Result.saveFail("座位锁定失败");
        }

        // 设置订单初始状态
        orderBase.setStatues(0); // 0表示待支付状态
        orderBase.setCreateTime(LocalDateTime.now());
        orderBase.setUpdateTime(LocalDateTime.now());
        // 同样需要设置订单详情的状态为0
        if (orderDetails != null && !orderDetails.isEmpty()) {
            for (OrderDetail detail : orderDetails) {
                detail.setStatues(0); // 0表示待支付状态
                detail.setCreateTime(LocalDateTime.now());
                detail.setUpdateTime(LocalDateTime.now());
            }
        }

        try {
            boolean result = orderBaseService.saveOrderWithDetails(orderBase, orderDetails);
            if (result) {
                // 发送延时消息，15分钟后检查订单状态
                rabbitTemplate.convertAndSend("delay_exchange", "order.timeout", orderBase.getOrderId(), message -> {
                    message.getMessageProperties().setHeader("x-delay", 900000); // 延时15分钟(毫秒)
                    return message;
                });

                // 查询刚保存的订单信息并返回
                OrderBase savedOrder = orderBaseService.getOrderById(orderBase.getOrderId());
                return Result.saveSuccess(savedOrder);
            } else {
                // 保存失败时释放座位
                seatStatusService.releaseSeats(orderBase.getScheduleId(), orderBase.getSeatCoordinates());
                return Result.saveFail("订单保存失败");
            }
        } catch (Exception e) {
            // 异常时释放座位
            seatStatusService.releaseSeats(orderBase.getScheduleId(), orderBase.getSeatCoordinates());
            return Result.saveFail("订单保存异常: " + e.getMessage());
        }
    }

    /**
     * 删除订单及详情（强制绑定）
     * @param id 订单ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}/with-details")
    public Result removeOrderWithDetails(@PathVariable Integer id) {
        try {
            // 获取订单信息
            OrderBase orderBase = orderBaseService.getOrderById(id);
            if (orderBase == null) {
                return Result.deleteFail("订单不存在");
            }

            // 释放座位
            seatStatusService.cancelBooking(
                    orderBase.getScheduleId(),
                    orderBase.getSeatCoordinates()
            );

            // 删除订单
            boolean result = orderBaseService.removeOrderWithDetails(id);
            if (result) {
                return Result.deleteSuccess("取消订单及详情成功");
            } else {
                return Result.deleteFail("取消订单失败");
            }
        } catch (Exception e) {
            return Result.deleteFail("取消订单异常: " + e.getMessage());
        }
    }


    // 更新订单
    @PutMapping
    public boolean updateOrder(@RequestBody OrderBase orderBase) {
        return orderBaseService.updateOrder(orderBase);
    }

    /**
     * 根据用户ID和状态查询订单及详情
     * @param userId 用户ID
     * @param status 订单状态
     * @return 包含订单基础信息和详情信息的VO列表
     */
    @GetMapping("/user/{userId}/status/{status}")
    public List<OrderBaseWithDetailsVO> getOrdersByUserIdAndStatusWithDetails(@PathVariable Integer userId, @PathVariable Integer status) {
        return orderBaseService.getOrdersByUserIdAndStatusWithDetails(userId, status);
    }

    /**
     * 根据用户ID查询所有状态订单及详情
     * @param userId 用户ID
     * @return 包含订单基础信息和详情信息的VO列表
     */
    @GetMapping("/user/{userId}/all-status")
    public List<OrderBaseWithDetailsVO> getOrdersByUserIdAndAllStatusWithDetails(@PathVariable Integer userId) {
        return orderBaseService.getOrdersByUserIdAndAllStatusWithDetails(userId);
    }

}
